import CryptoES from "crypto-es";
class WsCharts {
  ws = null;
  constructor(model, fn) {
    this.model = model;
    this.fn = fn;
  }
  test(msg) {
    this.fn(msg);
  }
  send(msg) {
    this.sparklite(msg);
  }
  sparklite(msg) {
    const host = 'spark-api.xf-yun.com';
    const path = '/v1.1/chat';
    const app_id = '1e13253e';
    const APISecret = 'NjZmNWE2Nzg1YTcwYWI2Njc5YWY5ZjY5';
    const APIKey = '86a7c023f4d129e86efd12f97a8527b5';
    const dateString = new Date().toGMTString();
    let tmp = "host: " + host + "\n"
    tmp += "date: " + dateString + "\n"
    tmp += "GET " + path + " HTTP/1.1"
    const signature = CryptoES.HmacSHA256(tmp, APISecret).toString(CryptoES.enc.Base64)
    const authorization_origin = btoa(`api_key="${APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`)
    const signUrl = `wss://${host}${path}?authorization=${authorization_origin}&date=${encodeURIComponent(dateString).replace(/%20/g, "+")}&host=${host}`
    this.ws = new WebSocket(signUrl)
    this.ws.onopen = () => {
      console.warn("连接成功",msg);
      this.fn("open");
      this.ws.send(JSON.stringify({
        "header": {
          "app_id": app_id,//替换成自己的app_id
          // "uid": "fd3f47e4-d",//最大长度32	每个用户的id，用于区分不同用户
        },
        "parameter": {
          "chat": {
            "domain": "lite",
            "temperature": 0.5,
            "max_tokens": 1024, //模型回答的tokens的最大长度
          }
        },
        "payload": {
          "message": {
            "text": msg
          }
        }
      }))
    };
    //后端设置心跳，会每间隔一定时间，触发一次，根据内容变化处理逻辑
    this.ws.onmessage = (e) => {
      console.warn('接收消息',e)
      const msg = JSON.parse(e.data);
      this.fn("msg", msg.payload.choices.text);
    };
    this.ws.onclose = (e) => {
      console.warn('连接关闭',e)
      //断连后每5秒重连一次
      this.fn("close");
    };
  }
}
export default WsCharts;